package jtalk.model;

import jtalk.controller.Properties;
import jtalk.logging.Logger;

public class ConnectionStatusListener implements org.jivesoftware.smack.ConnectionListener {

	private XMPPManager xmppManager = null;
	
	protected ConnectionStatusListener(XMPPManager xmppManager) {
		this.xmppManager = xmppManager;
	}
	
	public void connectionClosed() {
		xmppManager.firePropertyChange(Properties.AUTHENTICATED.toString(), null, false);
		xmppManager.firePropertyChange(Properties.CONNECTED.toString(), null, false);
		Logger.getLogger(this).info("Connection has been properly closed...");
	}

	public void connectionClosedOnError(Exception e) {
		xmppManager.firePropertyChange(Properties.AUTHENTICATED.toString(), null, false);
		xmppManager.firePropertyChange(Properties.CONNECTED.toString(), null, false);
		Logger.getLogger(this).error("Connection closed on error : " + e.getMessage());
	}

	public void reconnectingIn(int seconds) {		
		xmppManager.firePropertyChange(Properties.AUTHENTICATED.toString(), null, false);
		xmppManager.firePropertyChange(Properties.CONNECTED.toString(), null, false);
		Logger.getLogger(this).info("Connection closed, try to reconnect for " + seconds + " seconds");
	}

	public void reconnectionFailed(Exception e) {
		xmppManager.firePropertyChange(Properties.AUTHENTICATED.toString(), null, false);
		xmppManager.firePropertyChange(Properties.CONNECTED.toString(), null, false);
		Logger.getLogger(this).error("Connection reconnection has failed : " + e.getMessage());
	}

	public void reconnectionSuccessful() {		
		
		xmppManager.firePropertyChange(Properties.CONNECTED.toString(), null, true);
		
		
		if(xmppManager.isAuthenticated()) {
			xmppManager.firePropertyChange(Properties.AUTHENTICATED.toString(), null, true);
		}else {
			xmppManager.firePropertyChange(Properties.AUTHENTICATED.toString(), null, false);
		}
		
		Logger.getLogger(this).info("Connection has been successfully reconnected ...");
		
	}

}
